package com.xw.netty.basic;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * netty客户端
 * @ClassName NettyClient
 * @Author liu zhiyong
 * @Date 2020/8/20 17:13
 * @Version 1.0
 */
public class NettyClient {

    public static void main(String[] args) throws InterruptedException {
        //1.创建线程组
        EventLoopGroup group = new NioEventLoopGroup();

        //2.创建客户端的启动助手
        Bootstrap client = new Bootstrap();

        client.group(group)//3.设置线程组
            .channel(NioSocketChannel.class)//4.设置客户端通道的实现类
            .handler(new ChannelInitializer<SocketChannel>(){//5.创建通道初始化对象

                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    //6.往Pipeline链中添加自定义的业务处理类
                    socketChannel.pipeline().addLast(new NettyClientHandler());
                }
            });

        System.out.println("Client is ready...");

        //7.启动客户端连接服务器客户端
        ChannelFuture future = client.connect("127.0.0.1", 9999).sync();//connect方法是异步的，但是后面调用搞的sync()方法在主线程main方法里是同步阻塞的，只有连接成功后，才能执行后面的代码
        System.out.println(".........Client - 连接成功.........");

        //8.关闭连接(异步非阻塞)
        future.channel().closeFuture().sync();
    }

}
